﻿using UnityEngine;
using System.Collections;
using XLua;
using cframework_xlua;

namespace Game
{
    public class LuaEnvMgrBehaviour : MonoBehaviour
    {
        void Update()
        {
            LuaEnvMgr.Update();
        }

        private void OnDestroy()
        {
            //LuaEnvMgr.Destroy();
        }
    }

    public static class LuaEnvMgr
    {
        static LuaEnv luaenv;
        
        public static string[] luaDirs = new string[] { "Assets/Game/lua", "Assets/fwdata/Game/lua" };

        public static LuaEnv GetLuaEnv()
        {
            InitLua();
            return luaenv;
        }


        static void InitLua()
        {
            if(luaenv != null) { return; }

            GameObject obj = new GameObject("luamgr_updater");
            obj.AddComponent<LuaEnvMgrBehaviour>();

            luaenv = new LuaEnv();
            luaenv.AddLoader((ref string filename) =>
            {
                foreach (var d in luaDirs)
                {
                    if (AppManager.GetAppInfo().enable_hotupdate)
                    {
                        var filepath = $"{d}/" + filename + ".lua.txt";
                        var luaText = HotUpdateDllMgr.GetBundle()?.LoadAsset<TextAsset>(filepath);
                        if (luaText != null)
                        {
                            return luaText.bytes;
                        }
                    }
                }

                foreach (var d in luaDirs)
                {
                    var luaText = Resources.Load<TextAsset>("lua/" + filename + ".lua");
                    if (luaText != null)
                    {
                        return luaText.bytes;
                    }
                }


                if (Application.isEditor)
                {
                    foreach (var d in luaDirs)
                    {
                        var filepath = System.IO.Path.GetDirectoryName(Application.dataPath) + $"/{d}/" + filename + ".lua.txt";
                        if (System.IO.File.Exists(filepath))
                        {
                            return System.IO.File.ReadAllBytes(filepath);
                        }
                    }
                }

                return null;
            });

            luaenv.DoString("require('base/ClassUtil')");
            luaenv.DoString("require('base/SerializeClassUtil')");
        }



        // Update is called once per frame
        public static void Update()
        {
            InitLua();

            if (luaenv != null)
            {
                luaenv.Tick();
            }
        }

        public static void Destroy()
        {
            if (luaenv != null)
            {
                luaenv.Dispose();
                luaenv = null;
            }
        }
    }
}
